package com.gonsin.gview.logic.parser;

import com.gonsin.gview.annotations.GContext;
import com.gonsin.gview.annotations.enums.*;
import com.gonsin.gview.annotations.impl.*;
import com.gonsin.gview.annotations.interfaces.*;
import com.gonsin.gview.annotations.model.DownloadResponse;
import com.gonsin.gview.annotations.model.ViewRequest;
import com.gonsin.gview.logic.exceptions.BaseGViewException;
import com.gonsin.gview.logic.model.ActionPo;
import com.gonsin.gview.logic.model.DataSourcePo;
import com.gonsin.gview.logic.services.*;
import com.gonsin.gview.logic.services.dynamicData.DataUtils;
import com.gonsin.gview.logic.utils.SpringUtil;
import com.gonsin.gview.model.*;
import com.gonsin.gview.model.data.*;
import com.gonsin.gview.model.dynamic.DynamicButton;
import com.gonsin.gview.model.dynamic.DynamicProp;
import com.gonsin.gview.model.dynamic.DynamicView;
import com.gonsin.gview.model.dynamic.data.*;
import com.gonsin.gview.model.dynamic.form.*;
import com.gonsin.gview.model.dynamic.tab.*;
import com.gonsin.gview.model.dynamic.table.*;
import com.gonsin.gview.model.form.*;
import com.gonsin.gview.model.struct.EnumItem;
import com.gonsin.gview.model.tab.GLinkBoardModel;
import com.gonsin.gview.model.tab.GTabModel;
import com.gonsin.gview.model.tab.GTabModels;
import com.gonsin.gview.model.table.*;
import com.gonsin.i18n.logic.T;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * View转换器
 */
@Slf4j
@Component
public class DynamicViewParser implements IGViewParser<DynamicView>{


    @Autowired private GViewDataServiceImpl dataService;
    @Autowired private GViewActionServiceImpl actionService;
    @Autowired private GViewGlobalEnumsServiceImpl globalEnumsService;
    @Autowired private GViewCoreServiceImpl coreService;

    @Autowired private DataUtils dataUtils;

    @Autowired(required = false) IViewPermissionHandler permissionHandler;
//    @Autowired private GViewFutureBindingService bindingService;

    /**
     * 解析动态GView
     *
     * @param context
     * @param view
     * @return
     */
    @Override
    public GViewModel parse(GContext context, DynamicView view) {


        view.beforeCreate(context);


        GViewModel model = new GViewModel();
        model.setViewName(context.getViewName());
        model.setTitle(view.title(context));
        model.setProps(view.props());

        model.setContext(context);
        model.setServerProps(view.serverProps(context));


        if(view instanceof DynamicTableView){

            GBoardModel board = initTableBoard(context, (DynamicTableView)view);
            model.setBoards(Collections.singletonList(board));
            return model;
        }

        if(view instanceof DynamicFormView){
            GBoardModel board = initFormView(context, (DynamicFormView) view);
            model.setBoards(Collections.singletonList(board));
            return model;
        }

        if(view instanceof DynamicTabView){
            GBoardModel board = initTabBoards(context, (DynamicTabView) view);
            model.setBoards(Collections.singletonList(board));
            return model;
        }


        return model;
    }


    /**
     * 初始化多个tab
     */
    private GTabModels initTabBoards(GContext context, DynamicTabView tab) {

        GTabModels models = new GTabModels();
        models.setBoardType("tab");
        models.setTabs(new ArrayList<>());
        List<DynamicView> tabs = tab.tabs(context);
        if(!CollectionUtils.isEmpty(tabs)){
            for(DynamicView t : tabs){
                t.beforeCreate(context);

                GTabModel m = new GTabModel();
                m.setTitle(t.title(context));
                m.setProps(t.props());
                m.setServerProps(t.serverProps(context));
                if(t instanceof DynamicTableView){
                    m.setBoard(initTableBoard(context, (DynamicTableView)t));
                } else if(t instanceof DynamicFormView){
                    m.setBoard(initFormView(context, (DynamicFormView)t));
                } else if(t instanceof DynamicTabItemName) {

                    // TODO 这种写法，只会支持静态的GView，不能支持动态GView
                    IViewModelHolder v = coreService.findViewByName(((DynamicTabItemName)t).getViewName());
                    ViewRequest request = new ViewRequest(context.getRequest(), context.getResponse(), context.getProps());
                    GViewModel itemModel = v.getViewModel(request, permissionHandler);
                    m.setBoard(itemModel.getBoards().get(0));
                } else if(t instanceof DynamicTabItemLink){
                    m.setBoard(initLinkBoard(context, ((DynamicTabItemLink)t).link(context)));
//                } else if(t instanceof DynamicTabView){
//                    m.setBoard(initLinkBoard(context, ((DynamicTabItemLink)t).link()));
                } else {
                    throw new BaseGViewException(String.format("【%s】中的tabs() 必须返回 DynamicFromView DynamicTableView DynamicTabItemLink DynamicTabItemName 其中之一", context.getViewName()));
                }
                models.getTabs().add(m);
            }
        }

        return models;
    }


    /**
     * 初始化一个link板块
     */
    private GBoardModel initLinkBoard(GContext context, String link) {
        GLinkBoardModel boardModel = new GLinkBoardModel();
        boardModel.setLink(link);
        return boardModel;
    }

//    /**
//     * 初始化@GTab
//     */
//    private GBoardModel initTabBoard(GContext context, DynamicTabView tab) {
//        List<DynamicView> tabs = tab.tabs();
//        if(!CollectionUtils.isEmpty(tabs)){
//            GTabModels model = new GTabModels();
//            List<GTabModel> list = new ArrayList<>();
//            for(DynamicView t : tabs){
//                GTabModel tabModel = new GTabModel();
//
//                // 如果是表单view
//                if(t instanceof DynamicFormView){
//                    GBoardModel board = initFormView(context, (DynamicFormView)t);
//                    tabModel.setBoard(board);
//
//                    // 如果是列表view
//                } else if(t instanceof DynamicTableView) {
//                    GBoardModel board = initTableBoard(context, (DynamicTableView)t);
//                    tabModel.setBoard(board);
//                }
//                list.add(tabModel);
//            }
//            model.setTabs(list);
//        }
//        return model;
//    }


    /**
     * 初始化列表页
     */
    private GBoardModel initTableBoard(GContext context, DynamicTableView table) {
        GTableBoardModel model = new GTableBoardModel();

        model.setBoardType("table");
        model.setCount(table.count(context));

        GHeaderModel header = new GHeaderModel();
        DynamicHeader gHeader = table.header(context);
        header.setButtons(new ArrayList<>());
        if(!CollectionUtils.isEmpty(gHeader.getButtons())){
            for(DynamicButton button : gHeader.getButtons()){
                GButtonModel buttonModel = initButton(context, button);
                if(buttonModel == null){
                    continue;
                }
                header.getButtons().add(buttonModel);
            }
        }

        if(gHeader.getSearchBar() != null){
            GSearchBarModel searchBar = new GSearchBarModel();
            header.setSearchBar(searchBar);
            searchBar.setFilters(new ArrayList<>());
            DynamicSearchBar gSearchBar = gHeader.getSearchBar();
            if(!CollectionUtils.isEmpty(gSearchBar.getFilters())){
                for(DynamicSearchFilter gSearchFilter : gSearchBar.getFilters()){

                    // 下拉选择框
                    if(gSearchFilter instanceof DynamicSelector){
                        GSelectorModel selector = initSelector(context, (DynamicSelector)gSearchFilter);
                        searchBar.getFilters().add(selector);
                    }

                    // 时间选择框
                    if(gSearchFilter instanceof DynamicTimeSelector){
                        GTimeSelectorModel selector = initTimeSelector(context, (DynamicTimeSelector)gSearchFilter);
                        searchBar.getFilters().add(selector);
                    }

                    // 时间选择框
                    if(gSearchFilter instanceof DynamicDelaySelector){
                        GDelaySelectorModel selector = initDelaySelector(context, (DynamicDelaySelector)gSearchFilter);
                        searchBar.getFilters().add(selector);
                    }

                    // 日期选择框
                    if(gSearchFilter instanceof DynamicDateTimeSelector){
                        GDateTimeSelectorModel selector = initDateTimeSelector(context, (DynamicDateTimeSelector)gSearchFilter);
                        searchBar.getFilters().add(selector);
                    }

                    // 日期时间选择框
                    if(gSearchFilter instanceof DynamicDateSelector){
                        GDateSelectorModel selector = initDateSelector(context, (DynamicDateSelector)gSearchFilter);
                        searchBar.getFilters().add(selector);
                    }

                    // 文本框
                    if(gSearchFilter instanceof DynamicTextInput){
                        GTextInputModel textInput = initTextInput(context, (DynamicTextInput)gSearchFilter);
                        searchBar.getFilters().add(textInput);
                    }
                }
            }

        }
        model.setHeader(header);

        //
        GTableDataModel dataModel = initTableData(context, table.tableData(context));
        model.setTableData(dataModel);


        //
        model.setColumns(new ArrayList<>());
        if(!CollectionUtils.isEmpty(table.columns(context))){
            for(DynamicColumn column : table.columns(context)){
                GColumnModel columnModel = initColumn(context, column);
                model.getColumns().add(columnModel);

            }
        }
        return model;
    }


    /**
     * 初始化on change对应的buttonId
     * @param context
     * @param actionName
     * @return
     */
    private String initOnChangeButtonId(GContext context, String actionName){
        String buttonId = IdUtils.nextButtonId(actionName);
        bindButtonActionInFuture(context, buttonId, actionName);
        return buttonId;
    }


    /**
     * 初始化时间选择器
     */
    private GTimeSelectorModel initTimeSelector(GContext context, DynamicTimeSelector timeSelector) {
        GTimeSelectorModel selectorModel = new GTimeSelectorModel();
        selectorModel.setName(timeSelector.getName());
        selectorModel.setItemType("time_selector");
        selectorModel.setKeyName(timeSelector.getKeyName());
        selectorModel.setRequired(timeSelector.isRequired());
        selectorModel.setPlaceholder(timeSelector.getPlaceholder());
        selectorModel.setShowIf(timeSelector.getShowIf());
        selectorModel.setDisableIf(timeSelector.getDisableIf());
//        selectorModel.setOnChangeAction(timeSelector.getOnChangeAction());
//        checkExistAction(context,  timeSelector.getOnChangeAction());

        if(StringUtils.isNotEmpty(timeSelector.getOnChangeAction())){

            selectorModel.setButtonId(initOnChangeButtonId(context, timeSelector.getOnChangeAction()));
        }
        return selectorModel;
    }
    /**
     * 初始化时间选择器
     */
    private GDelaySelectorModel initDelaySelector(GContext context, DynamicDelaySelector timeSelector) {
        GDelaySelectorModel selectorModel = new GDelaySelectorModel();
        selectorModel.setName(timeSelector.getName());
        selectorModel.setItemType("delay_selector");
        selectorModel.setKeyName(timeSelector.getKeyName());
        selectorModel.setRequired(timeSelector.isRequired());
        selectorModel.setPlaceholder(timeSelector.getPlaceholder());
        selectorModel.setShowIf(timeSelector.getShowIf());
        selectorModel.setDisableIf(timeSelector.getDisableIf());
//        selectorModel.setOnChangeAction(timeSelector.getOnChangeAction());
//        checkExistAction(context,  timeSelector.getOnChangeAction());

        if(StringUtils.isNotEmpty(timeSelector.getOnChangeAction())){

            selectorModel.setButtonId(initOnChangeButtonId(context, timeSelector.getOnChangeAction()));
        }
        return selectorModel;
    }
    /**
     * 初始化时间选择器
     */
    private GTagModel initTag(GContext context, DynamicTag tag) {
        GTagModel selectorModel = new GTagModel();
        selectorModel.setName(tag.getName());
        selectorModel.setItemType("tag");
        selectorModel.setKeyName(tag.getKeyName());
        selectorModel.setRequired(tag.isRequired());
        selectorModel.setPlaceholder(tag.getPlaceholder());
        selectorModel.setShowIf(tag.getShowIf());
        selectorModel.setDisableIf(tag.getDisableIf());
//        selectorModel.setOnChangeAction(timeSelector.getOnChangeAction());
//        checkExistAction(context,  timeSelector.getOnChangeAction());

        if(StringUtils.isNotEmpty(tag.getOnChangeAction())){

            selectorModel.setButtonId(initOnChangeButtonId(context, tag.getOnChangeAction()));
        }
        return selectorModel;
    }

    /**
     * 初始化日期选择器
     */
    private GDateSelectorModel initDateSelector(GContext context, DynamicDateSelector timeSelector) {
        GDateSelectorModel selectorModel = new GDateSelectorModel();
        selectorModel.setName(timeSelector.getName());
        selectorModel.setKeyName(timeSelector.getKeyName());
        selectorModel.setPlaceholder(timeSelector.getPlaceholder());
        selectorModel.setRequired(timeSelector.isRequired());
        selectorModel.setShowIf(timeSelector.getShowIf());
        selectorModel.setDisableIf(timeSelector.getDisableIf());
//        selectorModel.setOnChangeAction(timeSelector.getOnChangeAction());
//        checkExistAction(context,  timeSelector.getOnChangeAction());

        if(StringUtils.isNotEmpty(timeSelector.getOnChangeAction())){

            selectorModel.setButtonId(initOnChangeButtonId(context, timeSelector.getOnChangeAction()));
        }
        return selectorModel;
    }

    /**
     * 初始化日期时间选择器
     */
    private GDateTimeSelectorModel initDateTimeSelector(GContext context, DynamicDateTimeSelector timeSelector) {
        GDateTimeSelectorModel selectorModel = new GDateTimeSelectorModel();
        selectorModel.setName(timeSelector.getName());
        selectorModel.setKeyName(timeSelector.getKeyName());
        selectorModel.setPlaceholder(timeSelector.getPlaceholder());
        selectorModel.setRequired(timeSelector.isRequired());
        selectorModel.setShowIf(timeSelector.getShowIf());
        selectorModel.setDisableIf(timeSelector.getDisableIf());
//        selectorModel.setOnChangeAction(timeSelector.getOnChangeAction());
//        checkExistAction(context,  timeSelector.getOnChangeAction());


        if(StringUtils.isNotEmpty(timeSelector.getOnChangeAction())){

            selectorModel.setButtonId(initOnChangeButtonId(context, timeSelector.getOnChangeAction()));

        }
        return selectorModel;
    }

    private void bindButtonActionInFuture(GContext context, String buttonId, String actionName) {
        ActionPo action = coreService.findActionByName(actionName);
        if(action == null){
            throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                    , context.getViewName(), actionName));
        }
        actionService.putConfirmAction(context, buttonId,
                action.getActionService(), action.getActionMethod());
    }

    private GColumnModel initColumn(GContext context, DynamicColumn column) {
        GColumnModel columnModel = new GColumnModel();
        columnModel.setColumnType(column.getColumnType().name());
        columnModel.setButtons(new ArrayList<>());
        columnModel.setFormItems(new ArrayList<>());
        if(!CollectionUtils.isEmpty(column.getButtons())){
            for(DynamicButton button : column.getButtons()){
                GButtonModel buttonModel = initButton(context, button);
                if(buttonModel == null){
                    continue;
                }
                columnModel.getButtons().add(buttonModel);
            }
        }
        if(!CollectionUtils.isEmpty(column.getFormItems())){
            for(DynamicFormItem item : column.getFormItems()){
                GFormItemModel itemModel = initFormItem(context, item);
                columnModel.getFormItems().add(itemModel);
            }
        }
        columnModel.setFormat(column.getFormat());
        columnModel.setName(column.getName());
        columnModel.setKeyName(column.getKeyName());
        columnModel.setValue(column.getValue());
        columnModel.setWeight(column.getWeight());


        switch(column.getColumnType()){
            case TEXT:
                break;
            case BUTTONS:
                if(CollectionUtils.isEmpty(column.getButtons())){
                    log.warn("按钮类型的column没有一个按钮");
                }
                break;
            case ENUMS:
                if(!CollectionUtils.isEmpty(column.getEnums())) {
                    columnModel.setEnums(initEnums(context, column.getEnums()));
                } else if(StringUtils.isNotEmpty(column.getEnumName())){
                    columnModel.setEnums(initEnumByName(context, column.getEnumName()));
                } else {
                    throw new BaseGViewException(String.format("【%s】里面的某个@GColumn设了columnType=ENUMS，但是没有设置enums 或 enumName"
                            , context.getViewName()));
                }
        }

        return columnModel;
    }

    private List<GEnumsModel> initEnumByName(GContext context, String enumName) {
        List<EnumItem> items = globalEnumsService.getEnums(enumName);
        if(items == null){
            throw new BaseGViewException(String.format("【%s】里面的某个@GColumn设了enumName=\"%s\"，但是没有找到【%s】"
                    , context.getViewName(), enumName, enumName));
        }
        List<GEnumsModel> result = new ArrayList<>();
        for(EnumItem e : items){
            GEnumsModel model = new GEnumsModel();
            model.setValue(e.getValue().toString());
            model.setType(EnumsType.TEXT.name());
            model.setText(e.getTitle());
            result.add(model);
        }
        return result;
    }


    private List<GEnumsModel> initEnums(GContext context, List<EnumItem> enums){
        List<GEnumsModel> result = new ArrayList<>();
        for(EnumItem e : enums){
            GEnumsModel model = new GEnumsModel();
            model.setValue(e.getValue().toString());
            model.setType(EnumsType.TEXT.name());
//            model.setIconUrl(e.iconUrl());
//            model.setIconSize(e.iconSize());
            model.setText(e.getTitle());
            result.add(model);
        }
        return result;
    }

    private GButtonModel initButton(GContext context, DynamicButton button) {
        if(button == null){
            return null;
        }
        GButtonModel buttonModel = new GButtonModel();

        buttonModel.setButtonStyle(button.getButtonStyle() == null ? ButtonStyle.DEFAULT.name() : button.getButtonStyle().name());
        buttonModel.setButtonType(button.getButtonType() == null ? ButtonType.DEFAULT.name() : button.getButtonType().name());
        if(button.getAction() == null){
            throw new BaseGViewException(String.format("【%s】里面的某个按钮没有设置action值"
                    , context.getViewName()));
        }
        buttonModel.setAction(button.getAction() == null ? ButtonAction.NONE.name() : button.getAction().name());
        buttonModel.setName(button.getName());
//        buttonModel.setDialogBoard(button.viewDialog());
        buttonModel.setIcon(button.getIcon());
        buttonModel.setLink(button.getLink());
        buttonModel.setView(button.getView());
//        buttonModel.setTarget(button.target());
        buttonModel.setDownloadUrl(button.getDownloadUrl());
        buttonModel.setTextColor(button.getTextColor());
        buttonModel.setShowIf(button.getShowIf());
        buttonModel.setFileUploadType(button.getFileUploadType());
        buttonModel.setDisableIf(button.getDisableIf());
        buttonModel.setConfirmMessage(button.getConfirmMessage());
        buttonModel.setContext(context);
        buttonModel.setOutLink(BooleanUtils.isTrue(button.getOutLink()));
        buttonModel.setPermission(button.getPermission());

        // 2024/06/24 新增，用于判断按钮的权限确定是否显示
        if(button.getPermission() != null && button.getPermission().length > 0){
            if(permissionHandler != null){
                if(!permissionHandler.handPermissions(context, button.getPermission(), buttonModel)){
                    return null;
                }
            }
        }

        switch(button.getAction()){
            case LINK:
                if(StringUtils.isEmpty(buttonModel.getLink())){
                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=link但是没有设置link"
                            , context.getViewName()));
                }
                buttonModel.setProps(initProps(button.getProps()));
                break;
            case VIEW_BY_DIALOG:
            case VIEW:
                if(StringUtils.isEmpty(buttonModel.getView()) && StringUtils.isEmpty(buttonModel.getLink())){
//                    throw new PageNotFoundException();
                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=view但是没有设置view"
                            , context.getViewName()));
                }

                if(!StringUtils.isEmpty(buttonModel.getView())){
                    if(coreService.findViewByName(buttonModel.getView()) == null){
                        //                    throw new BoardNotFoundException(buttonModel.getPage());
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=【%s】但是没有找不到该view"
                                , context.getViewName(), button.getAction().name()));
                    }
                    coreService.putViewButton(buttonModel.getView(), buttonModel);
                    buttonModel.setProps(initProps(button.getProps()));
                }
                break;
            case UPLOAD_FILE:
                buttonModel.setButtonId(IdUtils.nextButtonId());
                if(button.getFileAction() != EmptyFileActionImpl.class && button.getFileAction() != null){
                    actionService.putFileAction(context, buttonModel.getButtonId(), button.getFileAction());
                } else if(!StringUtils.isEmpty(button.getFileActionClass())){
                    try {
                        Class<? extends IFileActionListener> clazz =
                                (Class<? extends IFileActionListener>) ClassUtils.getClass(button.getFileActionClass());
                        actionService.putFileAction(context, buttonModel.getButtonId(), clazz);
                    } catch (ClassNotFoundException e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=upload_file但是没有找到对应的class【%s】"
                                , context.getViewName(), button.getFileActionClass()));
//                        throw new ActionClassNotFoundException(context, button.fileActionClass());
                    }
                } else if(!StringUtils.isEmpty(button.getActionName())){
                    String actionName = button.getActionName();
                    buttonModel.setButtonId(IdUtils.nextButtonId(actionName));

                    ActionPo action = coreService.findActionByName(actionName);
                    if(action == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=upload_file但是没有找到对应的actionName【%s】"
                                , context.getViewName(), button.getActionName()));
                    }
                    actionService.putFileAction(context, buttonModel.getButtonId(), button.getActionName(),
                            action.getActionService(), action.getActionMethod());
                } else {
                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=upload_file但是没有设上传事件"
                            , context.getViewName()));
                }
                buttonModel.setLimit(button.getLimit());
                buttonModel.setAccept(button.getAccept());
                buttonModel.setShowIf(button.getShowIf());
                buttonModel.setDisableIf(button.getDisableIf());
                buttonModel.setProps(initProps(button.getProps()));
                break;
            case DOWNLOAD:
                if(StringUtils.isEmpty(button.getActionName())) {
                    if (StringUtils.isEmpty(buttonModel.getDownloadUrl())) {
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=download但是没有设downloadUrl"
                                , context.getViewName()));
                    }
                    buttonModel.setProps(initProps(button.getProps()));
                } else {
                    String actionName = button.getActionName();
                    buttonModel.setButtonId(IdUtils.nextButtonId(actionName));
                    ActionPo action = coreService.findActionByName(actionName);
                    if(action == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action = download 但是没有找到对应的actionName【%s】"
                                , context.getViewName(), button.getActionName()));
//                        throw new ActionNotFoundException(context, actionName);
                    }
                    if(!DownloadResponse.class.equals(action.getReturnType())){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action = download 但是找到对应的actionName【%s】 返回类型不是 DownloadResponse "
                                , context.getViewName(), button.getActionName()));
                    }
                    actionService.putDownloadAction(context, buttonModel.getButtonId(), button.getActionName(),
                            action.getActionService(), action.getActionMethod());
//                    buttonModel.setDownloadUrl("/restapi/s09/gview/active/download?viewName=" + context.getViewName() + "&buttonId=" + buttonModel.getButtonId());
                }
                break;
//                if(StringUtils.isEmpty(buttonModel.getView())){
//                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=view_by_dialog,但是没有设view"
//                            , context.getViewName()));
//                }
//                buttonModel.setProps(initProps(button.getProps()));
////                if(!boardNameList.contains(buttonModel.getView())){
////                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=view_by_dialog,但是没有找到对应的view【%s】"
////                            , context.getViewName(), buttonModel.getView()));
////                }
//                buttonModel.setProps(initProps(button.getProps()));
//                break;
            case CLOSE_DIALOG:
                break;

            case BATCH:
                buttonModel.setButtonId(IdUtils.nextButtonId());
                if(button.getBatchAction() != EmptyBatchActionImpl.class && button.getBatchAction() != null){
                    actionService.putBatchAction(context, buttonModel.getButtonId(), button.getBatchAction());
                } else if(!StringUtils.isEmpty(button.getBatchActionClass())){
                    try {
                        Class<? extends IBatchActionListener> clazz =
                                (Class<? extends IBatchActionListener>) ClassUtils.getClass(button.getBatchActionClass());
                        actionService.putBatchAction(context, buttonModel.getButtonId(), clazz);
                    } catch (ClassNotFoundException e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=batch，但是但是找不到该类【%s】"
                                , context.getViewName(), button.getBatchActionClass()));
                    }
                } else if(!StringUtils.isEmpty(button.getActionName())){

                    String actionName = button.getActionName();
                    buttonModel.setButtonId(IdUtils.nextButtonId(actionName));
                    ActionPo action = coreService.findActionByName(actionName);
                    if(action == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=batch,但是没有找到对应的actionName【%s】"
                                , context.getViewName(), button.getActionName()));
                    }
                    actionService.putBatchAction(context, buttonModel.getButtonId(), action.getActionService(), action.getActionMethod());
                } else {
//                    throw new ActionNotSetException(context);
                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=batch,但是没有设置点击事件"
                            , context.getViewName()));
                }
                buttonModel.setProps(initProps(button.getProps()));
                break;

            // TODO 表单方式的提交

            case CONFIRM:
            case CONFIRM_AND_CLOSE:
                buttonModel.setButtonId(IdUtils.nextButtonId());
                if(button.getConfirmAction() != null){
                    actionService.putConfirmAction(context, buttonModel.getButtonId(), button.getConfirmAction());
                } else if(!StringUtils.isEmpty(button.getConfirmActionClass())){
                    try {
                        Class<? extends IConfirmActionListener> clazz =
                                (Class<? extends IConfirmActionListener>) ClassUtils.getClass(button.getConfirmActionClass());
                        actionService.putConfirmAction(context, buttonModel.getButtonId(), clazz);
                    } catch (ClassNotFoundException e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=confirm 或 action=confirm_and_close 但是没有找到class【%s】"
                                , context.getViewName(), button.getConfirmActionClass()));
                    }
                } else if(!StringUtils.isEmpty(button.getActionName())){
                    String actionName = button.getActionName();
                    buttonModel.setButtonId(IdUtils.nextButtonId(actionName));
                    ActionPo action = coreService.findActionByName(actionName);
                    if(action == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=confirm 或 action=confirm_and_close 但是没有找到actionName【%s】"
                                , context.getViewName(), button.getActionName()));
                    }
                    actionService.putConfirmAction(context, buttonModel.getButtonId(), action.getActionService(), action.getActionMethod());
                } else {
                    throw new BaseGViewException(String.format("【%s】页面的某个按钮设了confirm但是没有设点击事件", context.getViewName()));
                }
                buttonModel.setProps(initProps(button.getProps()));
                break;

        }

        return buttonModel;
    }

    private List<GPropModel> initProps(List<DynamicProp> props) {
        List<GPropModel> propModels = new ArrayList<>();
        if(CollectionUtils.isEmpty(props)){
            return propModels;
        }
        for(DynamicProp prop : props){
            GPropModel model = new GPropModel();
            model.setValueName(prop.getValueName() == null ? "" : prop.getValueName());
            model.setKeyName(prop.getKeyName());
            propModels.add(model);
        }
        return propModels;
    }

    private GTextInputModel initTextInput(GContext context, DynamicTextInput textInput) {




        GTextInputModel textInputModel = new GTextInputModel();
        textInputModel.setInputType(textInput.getInputType() == null ? InputType.TEXT.name() : textInput.getInputType().name());
        textInputModel.setName(textInput.getName());
        textInputModel.setKeyName(textInput.getKeyName());
        textInputModel.setPlaceholder(textInput.getPlaceholder());
        textInputModel.setRequired(textInput.isRequired());
        textInputModel.setRegular(textInput.getRegular());
        textInputModel.setRegularMessage(textInput.getRegularMessage());
        textInputModel.setShowIf(textInput.getShowIf());
        textInputModel.setDisableIf(textInput.getDisableIf());
//        textInputModel.setOnChangeAction(textInput.getOnChangeAction());
//        checkExistAction(context,  textInput.getOnChangeAction());

        if(StringUtils.isNotEmpty(textInput.getOnChangeAction())){

            textInputModel.setButtonId(initOnChangeButtonId(context, textInput.getOnChangeAction()));
        }
        if(textInput.getSimpleListData() != null){
            textInputModel.setSimpleListData(initSimpleListData(context, textInput.getSimpleListData()));
        }
        return textInputModel;
    }


    private GFormItemModel initFormItem(GContext context, DynamicFormItem item){
        // 隐藏数据
        if(item instanceof DynamicHidden){
            return initHidden((DynamicHidden) item);

            // 多选下拉框
        } else if(item instanceof DynamicMultiSelector){
            return initMultiSelector(context, (DynamicMultiSelector) item);

            // 树状多选下拉框
        } else if(item instanceof DynamicMultiTreeSelector){
            return initMultiTreeSelector(context, (DynamicMultiTreeSelector) item);

            // 复选框
        } else if(item instanceof DynamicCheckBox){
            return initCheckBox(context, (DynamicCheckBox) item);

            // switch滑块
        } else if(item instanceof DynamicSwitch){
            return initSwitch(context, (DynamicSwitch) item);

            // 文件上传框
        } else if(item instanceof DynamicFile){
            return initFile((DynamicFile) item);

            // 单选框
        } else if(item instanceof DynamicRadio){
            return initRadio(context, (DynamicRadio) item);

            // 富文本框
        } else if(item instanceof DynamicRichText){
            return initRichText((DynamicRichText) item);

            // 下拉框
        } else if(item instanceof DynamicSelector){
            return initSelector(context, (DynamicSelector) item);

            // 文本框
        } else if(item instanceof DynamicTextInput){
            return initTextInput(context, (DynamicTextInput) item);

            // 树状复选框
        } else if(item instanceof DynamicTreeCheckBox){
            return initTreeCheckBox(context,(DynamicTreeCheckBox) item);

            // 树状选择框
        } else if(item instanceof DynamicTreeSelector){
            return initTreeSelector(context,(DynamicTreeSelector) item);

            // 静态文本框
        } else if(item instanceof DynamicLabel) {
            return initLabel(context, (DynamicLabel) item);

            // 时间选择器
        } else if(item instanceof DynamicImage) {
            return initImage(context, (DynamicImage) item);

            // 时间选择器
        }else if(item instanceof DynamicTimeSelector){
            return initTimeSelector(context, (DynamicTimeSelector) item);

            // 时长选择器
        }else if(item instanceof DynamicDelaySelector){
            return initDelaySelector(context, (DynamicDelaySelector) item);

            // 标签
        }else if(item instanceof DynamicTag){
            return initTag(context, (DynamicTag) item);

            // 时长选择器
        }else if(item instanceof DynamicDateSelector){
            return initDateSelector(context, (DynamicDateSelector) item);

            // 日期时间选择器
        }else if(item instanceof DynamicDateTimeSelector){
            return initDateTimeSelector(context, (DynamicDateTimeSelector) item);

            // 分隔线
        } else if(item instanceof DynamicLine){
            return initLine(context, (DynamicLine) item);
        } else if(item instanceof DynamicBlockStart){
            return initBlockStart(context, (DynamicBlockStart) item);
        } else if(item instanceof DynamicBlockEnd){
            return initBlockEnd(context, (DynamicBlockEnd) item);
        }

        throw new BaseGViewException(String.format("在【%s】中，无法识别标签类型【%s】", context.getViewName(), item.toString()));
    }

    /**
     * 初始化表单页
     */
    private GBoardModel initFormView(GContext context, DynamicFormView form) {
        GFormBoardModel model = new GFormBoardModel();
        model.setBoardType("form");
        GButtonModel buttonModel = initButton(context, form.cancelButton(context));
        if(buttonModel != null){
            model.setCancelButton(buttonModel);
        }


        buttonModel = initButton(context, form.okButton(context));
        if(buttonModel != null){
            if(StringUtils.isEmpty(buttonModel.getName())){
                buttonModel.setName("确定");
            }
            model.setOkButton(buttonModel);
        }
        model.setFormItems(new ArrayList<>());
        DynamicData data = form.data(context);
        if(data != null){

            // 数据的 dataId 一直创建，如果有现成的，就不用创建
            model.setData(initData(context, data));

        }
        List<DynamicFormItem> items = form.formItems(context);
        if(!CollectionUtils.isEmpty(items)){
            for(DynamicFormItem item : items){
                model.getFormItems().add(initFormItem(context, item));
            }
        }
        return model;
    }


    /**
     * 初始化分割线
     */
    private GLineModel initLine(GContext context, DynamicLine line) {
        GLineModel model = new GLineModel();
        model.setItemType("line");
        model.setName(line.getName());
        model.setShowIf(line.getShowIf());
        return model;
    }


    /**
     * 初始化分割线
     */
    private GBlockStartModel initBlockStart(GContext context, DynamicBlockStart blockStart) {
        GBlockStartModel model = new GBlockStartModel();
        model.setItemType("block_start");
        model.setName(blockStart.getName());
        model.setShowIf(blockStart.getShowIf());
        return model;
    }


    /**
     * 初始化分割线
     */
    private GBlockStartModel initBlockEnd(GContext context, DynamicBlockEnd blockEnd) {
        GBlockStartModel model = new GBlockStartModel();
        model.setItemType("block_start");
        model.setName(blockEnd.getName());
        model.setShowIf(blockEnd.getShowIf());
        return model;
    }


    /**
     * 初始化静态文本框
     */
    private GLabelModel initLabel(GContext context, DynamicLabel label) {
        GLabelModel model = new GLabelModel();
        model.setItemType("label");
        model.setKeyName(label.getKeyName());
        model.setName(label.getName());
        model.setValue(label.getValue());
        model.setShowIf(label.getShowIf());
        return model;
    }


    /**
     * 初始化静态文本框
     */
    private GImageModel initImage(GContext context, DynamicImage image) {
        GImageModel model = new GImageModel();
        model.setItemType("image");
        model.setKeyName(image.getKeyName());
        model.setName(image.getName());
        model.setValue(image.getValue());
        model.setShowIf(image.getShowIf());
        return model;
    }

    private GTreeSelectorModel initTreeSelector(GContext context, DynamicTreeSelector selector) {
        GTreeSelectorModel radioModel = new GTreeSelectorModel();
        radioModel.setName(selector.getName());
        radioModel.setKeyName(selector.getKeyName());
        radioModel.setRequired(selector.isRequired());
        radioModel.setShowIf(selector.getShowIf());
        radioModel.setDisableIf(selector.getDisableIf());
//        radioModel.setOnChangeAction(selector.getOnChangeAction());
//        checkExistAction(context,  selector.getOnChangeAction());

        if(StringUtils.isNotEmpty(selector.getOnChangeAction())){

            radioModel.setButtonId(initOnChangeButtonId(context, selector.getOnChangeAction()));
        }


        DynamicTreeData treeData = selector.getTreeData();
        if(treeData == null){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @GTreeCheckBox 没有设 treeData ",
                    context.getViewName()));
        }

        GTreeDataModel dataModel = initTreeSelectorData(context, treeData);
        radioModel.setTreeData(dataModel);

        return radioModel;
    }

    private GTreeCheckBoxModel initTreeCheckBox(GContext context, DynamicTreeCheckBox treeCheckBox) {
        GTreeCheckBoxModel radioModel = new GTreeCheckBoxModel();
        radioModel.setName(treeCheckBox.getName());
        radioModel.setKeyName(treeCheckBox.getKeyName());
        radioModel.setRequired(treeCheckBox.isRequired());
        radioModel.setShowIf(treeCheckBox.getShowIf());
        radioModel.setDisableIf(treeCheckBox.getDisableIf());
//        radioModel.setOnChangeAction(treeCheckBox.getOnChangeAction());
//        checkExistAction(context,  treeCheckBox.getOnChangeAction());

        if(StringUtils.isNotEmpty(treeCheckBox.getOnChangeAction())){

            radioModel.setButtonId(initOnChangeButtonId(context, treeCheckBox.getOnChangeAction()));
        }


        DynamicTreeData treeData = treeCheckBox.getTreeData();
        if(treeData == null){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @GTreeCheckBox 没有设 treeData ",
                    context.getViewName()));
        }

        GTreeDataModel dataModel = initTreeSelectorData(context, treeData);
        radioModel.setTreeData(dataModel);

        return radioModel;
    }

    private GRichTextModel initRichText(DynamicRichText richText) {
        GRichTextModel textModel = new GRichTextModel();
        textModel.setColumn(richText.getColumn());
        textModel.setKeyName(richText.getKeyName());
        textModel.setName(richText.getName());
        textModel.setRequired(richText.isRequired());
        textModel.setShowIf(richText.getShowIf());
        textModel.setDisableIf(richText.getDisableIf());
        return textModel;
    }

    private GFormItemModel initRadio(GContext context, DynamicRadio radio) {
        GRadioModel radioModel = new GRadioModel();
        radioModel.setName(radio.getName());
        radioModel.setKeyName(radio.getKeyName());
        radioModel.setRequired(radio.isRequired());
        radioModel.setPlaceholder(radio.getPlaceholder());
        radioModel.setShowIf(radio.getShowIf());
        radioModel.setDisableIf(radio.getDisableIf());
//        radioModel.setOnChangeAction(radio.getOnChangeAction());
//        checkExistAction(context,  radio.getOnChangeAction());

        if(StringUtils.isNotEmpty(radio.getOnChangeAction())){

            radioModel.setButtonId(initOnChangeButtonId(context, radio.getOnChangeAction()));
        }


        DynamicListData dynamicData = radio.getListData();
        if(dynamicData == null){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @GRadio 没有设 listData ",
                    context.getViewName()));
        }

        GListDataModel dataModel = initListData(context, dynamicData);
        radioModel.setListData(dataModel);

        return radioModel;
    }


    /**
     * 文件上传框初始化
     */
    private GFileModel initFile(DynamicFile file) {
        GFileModel fileModel = new GFileModel();
        fileModel.setAccept(file.getAccept());
        fileModel.setShowIf(file.getShowIf());
        fileModel.setDisableIf(file.getDisableIf());
        fileModel.setKeyName(file.getKeyName());
        String filenameKeyName = file.getFilenameKeyName();
        if(StringUtils.isEmpty(filenameKeyName)){
            fileModel.setFilenameKeyName("xxx_" + fileModel.getKeyName());
        }else {
            fileModel.setFilenameKeyName(file.getFilenameKeyName());
        }
        fileModel.setLimit(file.getLimit());
        fileModel.setName(file.getName());
        fileModel.setFileUploadType(file.getFileUploadType());
        fileModel.setRequired(file.isRequired());
        fileModel.setPlaceholder(file.getPlaceholder());
        fileModel.setMaxSize(file.getMaxSize());
        return fileModel;
    }

    private GCheckBoxModel initCheckBox(GContext context, DynamicCheckBox checkBox) {
        GCheckBoxModel checkBoxModel = new GCheckBoxModel();
        checkBoxModel.setName(checkBox.getName());
        checkBoxModel.setKeyName(checkBox.getKeyName());
        checkBoxModel.setRequired(checkBox.isRequired());
        checkBoxModel.setShowIf(checkBox.getShowIf());
        checkBoxModel.setDisableIf(checkBox.getDisableIf());
//        checkBoxModel.setOnChangeAction(checkBox.getOnChangeAction());
//        checkExistAction(context,  checkBox.getOnChangeAction());

        if(StringUtils.isNotEmpty(checkBox.getOnChangeAction())){

            checkBoxModel.setButtonId(initOnChangeButtonId(context, checkBox.getOnChangeAction()));
        }
        return checkBoxModel;
    }

    private GSwitchBoxModel initSwitch(GContext context, DynamicSwitch gSwitch) {
        GSwitchBoxModel checkBoxModel = new GSwitchBoxModel();
        checkBoxModel.setName(gSwitch.getName());
        checkBoxModel.setKeyName(gSwitch.getKeyName());
        checkBoxModel.setRequired(gSwitch.isRequired());
        checkBoxModel.setShowIf(gSwitch.getShowIf());
        checkBoxModel.setDisableIf(gSwitch.getDisableIf());

        // 2024/06/24 新增，用于判断按钮的权限确定是否显示
        if(gSwitch.getPermission() != null && gSwitch.getPermission().length > 0){
            if(permissionHandler != null){
                if(!permissionHandler.handPermissions(context, gSwitch.getPermission(), checkBoxModel)){
                    return null;
                }
            }
        }

        if(StringUtils.isNotEmpty(gSwitch.getOnChangeAction())){

            checkBoxModel.setButtonId(initOnChangeButtonId(context, gSwitch.getOnChangeAction()));
        }
        return checkBoxModel;
    }

    private GMultiTreeSelectorModel initMultiTreeSelector(GContext context, DynamicMultiTreeSelector selector) {
        GMultiTreeSelectorModel selectorModel = new GMultiTreeSelectorModel();
        selectorModel.setName(selector.getName());
        selectorModel.setItemType("multi_tree_selector");
        selectorModel.setKeyName(selector.getKeyName());
        selectorModel.setRequired(selector.isRequired());
        selectorModel.setShowIf(selector.getShowIf());
        selectorModel.setDisableIf(selector.getDisableIf());
//        selectorModel.setOnChangeAction(selector.getOnChangeAction());
//        checkExistAction(context,  selector.getOnChangeAction());

        if(StringUtils.isNotEmpty(selector.getOnChangeAction())){

            selectorModel.setButtonId(initOnChangeButtonId(context, selector.getOnChangeAction()));
        }

        DynamicTreeData treeData = selector.getTreeData();
        if(treeData == null){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @MultiTreeSelector 没有设 treeData ",
                    context.getViewName()));
        }

        GTreeDataModel dataModel = initTreeSelectorData(context, treeData);
        selectorModel.setTreeData(dataModel);

        return selectorModel;
    }

    /**
     * 初始化多选下拉框
     */
    private GMultiSelectorModel initMultiSelector(GContext context, DynamicMultiSelector selector) {
        GMultiSelectorModel selectorModel = new GMultiSelectorModel();
        selectorModel.setName(selector.getName());
        selectorModel.setItemType("multi_selector");
        selectorModel.setKeyName(selector.getKeyName());
        selectorModel.setRequired(selector.isRequired());
        selectorModel.setShowIf(selector.getShowIf());
        selectorModel.setDisableIf(selector.getDisableIf());
//        selectorModel.setOnChangeAction(selector.getOnChangeAction());
//        checkExistAction(context,  selector.getOnChangeAction());

        if(StringUtils.isNotEmpty(selector.getOnChangeAction())){

            selectorModel.setButtonId(initOnChangeButtonId(context, selector.getOnChangeAction()));
        }

//        if(selector.dataSource() == DataSource.STATIC){
//            String[] keyValue = selector.staticData();
//            if(keyValue == null){
//                throw new StaticNotFoundException(context.getBoardClass());
//            }
//
//            selectorModel.setValues(new ArrayList<>());
//            for(String kv : keyValue){
//                String[] kvs = kv.split("=");
//                if(kvs == null || kvs.length != 2){
//                    throw new StaticValueFormatException();
//                }
//                selectorModel.getValues().add(new KeyValue(kvs[0], kvs[1]));
//            }
//        } else if(selector.dataSource() == DataSource.DYNAMIC){

        DynamicListData dynamicData = selector.getListData();
        if(dynamicData == null){
//                throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @GMultiSelector 没有设 listData ",
                    context.getViewName()));
        }

        GListDataModel dataModel = initListData(context, dynamicData);
        selectorModel.setListData(dataModel);
//        }

        return selectorModel;
    }

    /***
     * 检查action是否有效
     * @param context
     * @param actionName
     */
    private void checkExistAction(GContext context, String actionName) {
        if(StringUtils.isEmpty(actionName)){
            return;
        }
         ActionPo action = coreService.findActionByName(actionName);
        if(action == null){
            throw new BaseGViewException(String.format("【%s】里面没有找到对应的actionName【%s】"
                    , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
        }
    }


    private GSelectorModel initSelector(GContext context, DynamicSelector selector) {
        GSelectorModel selectorModel = new GSelectorModel();
        selectorModel.setName(selector.getName());
        selectorModel.setKeyName(selector.getKeyName());
        selectorModel.setRequired(selector.isRequired());
        selectorModel.setShowIf(selector.getShowIf());
        selectorModel.setDisableIf(selector.getDisableIf());
//        selectorModel.setOnChangeAction(selector.getOnChangeAction());
//        checkExistAction(context,  selector.getOnChangeAction());


        if(StringUtils.isNotEmpty(selector.getOnChangeAction())){

            selectorModel.setButtonId(initOnChangeButtonId(context, selector.getOnChangeAction()));
        }

        DynamicListData listData = selector.getListData();
        if(listData == null){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @Selector 没有设 listData ",
                    context.getViewName()));
        }

        GListDataModel dataModel = initListData(context, listData);
        selectorModel.setListData(dataModel);
//        }

        return selectorModel;
    }


    /**
     * 初始化页面数据
     */
    @SneakyThrows
    private GTableDataModel initTableData(GContext context, DynamicTableData data) {
        GTableDataModel dataModel = new GTableDataModel();
        if(StringUtils.isEmpty(data.getKeyName())){
            throw new BaseGViewException(String.format("页面【%s】的 @GTableData 没有设 keyName"));
        }
        dataModel.setKeyName(data.getKeyName());

        if(StringUtils.isNotEmpty(data.getFromTableDataPickerClassName()) || data.getFromTableDataPicker() != null){

            String cn = data.getFromTableDataPickerClassName();
            Class pk = data.getFromTableDataPicker();

            String className = pk == null ? cn.substring(cn.lastIndexOf(".") + 1) : pk.getSimpleName();

            String dataId = dataService.findDataIdBySource(className);
            if(dataId == null){
                synchronized (this){
                    dataId = dataService.findDataIdBySource(className);
                    if(dataId == null){
                        dataId = IdUtils.nextDataId(className);
                        DataSourcePo source = coreService.findDataSourceByName(className);
                        if(source == null){
                            throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                                    , context.getViewName(), data.getFromTableDataPickerClassName()));
                        }


                        Class<? extends ITableDataPicker> clazz =
                                data.getFromTableDataPicker() == null
                                        ? (Class<? extends ITableDataPicker>) ClassUtils.getClass(data.getFromTableDataPickerClassName())
                                        : data.getFromTableDataPicker();


                        ITableDataPicker picker = SpringUtil.getBean(clazz);
                        if(picker == null){
                            try {
                                picker = clazz.newInstance();
                            } catch (Exception e) {
                                log.error(e.toString(), e);
                                throw new BaseGViewException(String.format("无法创建类【%s】", clazz.getName()));
                            }
                        }

                        dataService.readyTableDataByPicker(context, dataId, picker);
                    }
                }
            }
            dataModel.setDataId(dataId);

        } else if(StringUtils.isNotEmpty(data.getFromDataSource())){

            String dataId = dataService.findDataIdBySource(data.getFromDataSource());
            if(dataId == null){
                synchronized (this){
                    dataId = dataService.findDataIdBySource(data.getFromDataSource());
                    if(dataId == null){
                        dataId = IdUtils.nextDataId(data.getFromDataSource());
                        String dataSource = data.getFromDataSource();
                        DataSourcePo source = coreService.findDataSourceByName(dataSource);
                        if(source == null){
                            throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                                    , context.getViewName(), data.getFromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
                        }
                        dataService.readyTableDataSource(context, dataId,
                                source.getSourceService(), source.getSourceMethod(), dataSource);
                    }
                }
            }
            dataModel.setDataId(dataId);


        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @GTableData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }


    /**
     * 初始化下拉数据
     */
    private GSimpleListDataModel initSimpleListData(GContext context, DynamicSimpleListData listData) {

        GSimpleListDataModel dataModel = new GSimpleListDataModel();

        if(StringUtils.isNotEmpty(listData.getFromSql())){
            String sql = listData.getFromSql();
            dataModel.setData(dataUtils.generalDataFromSql(sql, false, context.getRequest(), context.getResponse(), context.getProps()));

        } else if(StringUtils.isNotEmpty(listData.getFromListDataPickerClassName())){


            try {
                Class<? extends IDataPicker> clazz =
                    (Class<? extends IDataPicker>) ClassUtils.getClass(listData.getFromListDataPickerClassName());
                IDataPicker picker = SpringUtil.getBean(clazz);
                if(picker == null){
                    try {
                        picker = clazz.newInstance();
                    } catch (Exception e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("无法创建类【%s】", clazz.getName()));
                    }
                }
                dataModel.setData(picker.getData(context, null, context.getRequest(), context.getProps()));
            } catch (Exception ex) {
                throw new BaseGViewException(String.format("页面【%s】的 @GSimpleListData 找不到类【】 ",
                        context.getViewName(), listData.getFromListDataPickerClassName()));
            }
        } else if(listData.getFromListDataPicker() != null){

            dataModel.setData(listData.getFromListDataPicker().getData(context, null, context.getRequest(), context.getProps()));
        } else if(StringUtils.isNotEmpty(listData.getFromJson())){
            String dataId = IdUtils.nextDataId();
            dataModel.setDataId(dataId);
            String json = listData.getFromJson().trim();
            if(!json.startsWith("[")){
                throw new BaseGViewException(String.format("页面【%s】的 @DynamicListData 的json结构不对，json内容为【%s】 ",
                        context.getViewName(), json));
            }
            Object j = new GsonBuilder().create().fromJson(json, new TypeToken<List<Object>>(){}.getType());
            dataModel.setData(j);
        } else if(StringUtils.isNotEmpty(listData.getFromDataSource())){

            String dataId = dataService.findDataIdBySource(listData.getFromDataSource());
            if(dataId == null){
                synchronized (this){
                    dataId = dataService.findDataIdBySource(listData.getFromDataSource());
                    if(dataId == null){
                        dataId = IdUtils.nextDataId(listData.getFromDataSource());
                        String dataSource = listData.getFromDataSource();
                        DataSourcePo source = coreService.findDataSourceByName(dataSource);
                        if(source == null){
                            throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                                    , context.getViewName(), listData.getFromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
                        }
                        dataService.readyListDataSource(context, dataId,
                                source.getSourceService(), source.getSourceMethod(), dataSource);
                    }
                }
            }
            dataModel.setDataId(dataId);


        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @DynamicListData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }



    /**
     * 初始化下拉数据
     */
    private GListDataModel initListData(GContext context, DynamicListData listData) {
        GListDataModel dataModel = new GListDataModel();

        dataModel.setKeyName(listData.getKeyName());
        if("".equals(listData.getTitleName())){
            dataModel.setTitleName(listData.getKeyName());
        } else {
            dataModel.setTitleName(listData.getTitleName());
        }
        dataModel.setValueName(listData.getValueName());

        if(StringUtils.isNotEmpty(listData.getFromEnums())){
            String dataId = IdUtils.nextDataId();
            dataModel.setDataId(dataId);
            String enumName = listData.getFromEnums();
            dataService.readyEnumsData(context, dataId, enumName);
            dataModel.setKeyName("key");
            dataModel.setValueName("value");
            dataModel.setTitleName("title");
            return dataModel;
        }


        if(StringUtils.isEmpty(dataModel.getValueName())){
            throw new BaseGViewException(String.format("【%s】中@GListData必须添加value值", context.getViewName()));
        }

        if(StringUtils.isEmpty(dataModel.getKeyName())){
            throw new BaseGViewException(String.format("【%s】中@GListData必须添加key值", context.getViewName()));
        }

        if(StringUtils.isNotEmpty(listData.getFromSql())){
            String sql = listData.getFromSql();
            dataModel.setData(dataUtils.generalDataFromSql(sql, false, context.getRequest(), context.getResponse(), context.getProps()));

        } else if(StringUtils.isNotEmpty(listData.getFromListDataPickerClassName())){


            try {
                Class<? extends IDataPicker> clazz =
                        (Class<? extends IDataPicker>) ClassUtils.getClass(listData.getFromListDataPickerClassName());
                IDataPicker picker = SpringUtil.getBean(clazz);
                if(picker == null){
                    try {
                        picker = clazz.newInstance();
                    } catch (Exception e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("无法创建类【%s】", clazz.getName()));
                    }
                }
                dataModel.setData(picker.getData(context, null, context.getRequest(), context.getProps()));
            } catch (Exception ex) {
                throw new BaseGViewException(String.format("页面【%s】的 @GSimpleListData 找不到类【】 ",
                        context.getViewName(), listData.getFromListDataPickerClassName()));
            }


        } else if(listData.getFromListDataPicker() != null){

            dataModel.setData(listData.getFromListDataPicker().getData(context, null, context.getRequest(), context.getProps()));

        } else if(StringUtils.isNotEmpty(listData.getFromEnums())){

            String dataId = dataService.findDataIdBySource(listData.getFromEnums());
            if(dataId == null){
                synchronized (this){
                    dataId = dataService.findDataIdBySource(listData.getFromEnums());
                    if(dataId == null){
                        dataId = IdUtils.nextDataId(listData.getFromEnums());
                        String dataSource = listData.getFromEnums();
                        DataSourcePo source = coreService.findDataSourceByName(dataSource);
                        if(source == null){
                            throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                                    , context.getViewName(), listData.getFromEnums()));
                        }
                        dataService.readyEnumsData(context, dataId, listData.getFromEnums());
                    }
                }
            }
            dataModel.setDataId(dataId);
            return dataModel;


        } else if(StringUtils.isNotEmpty(listData.getFromJson())){


            String dataId = IdUtils.nextDataId();
            dataModel.setDataId(dataId);
            String json = listData.getFromJson().trim();
            if(!json.startsWith("[")){
                throw new BaseGViewException(String.format("页面【%s】的 @DynamicListData 的json结构不对，json内容为【%s】 ",
                        context.getViewName(), json));
            }
            List<Map<String, Object>> list = new GsonBuilder().create().fromJson(json, new TypeToken<List<Map<String, Object>>>(){}.getType());

            String titleName = dataModel.getTitleName();
            if (titleName == null || titleName.isEmpty()) {
                titleName = dataModel.getKeyName();
            }

            // 针对I18N做转换
            if(!StringUtils.isEmpty(titleName)){
                for(Map<String, Object> item : list) {
                    if (item == null) {
                        continue;
                    }
                    if (StringUtils.isEmpty(titleName)) {
                        continue;
                    }
                    Object title = item.get(titleName);
                    if (title != null && title instanceof String) {
                        title = T.t((String) title);
                        item.put(titleName, title);
                    }
                }
            }

            dataModel.setData(list);


        } else if(StringUtils.isNotEmpty(listData.getFromDataSource())){


            String dataId = dataService.findDataIdBySource(listData.getFromDataSource());
            if(dataId == null){
                synchronized (this){
                    dataId = dataService.findDataIdBySource(listData.getFromDataSource());
                    if(dataId == null){
                        dataId = IdUtils.nextDataId(listData.getFromDataSource());
                        String dataSource = listData.getFromDataSource();
                        DataSourcePo source = coreService.findDataSourceByName(dataSource);
                        if(source == null){
                            throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                                    , context.getViewName(), listData.getFromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
                        }
                        dataService.readyListDataSource(context, dataId,
                                source.getSourceService(), source.getSourceMethod(), dataSource);
                    }
                }
            }
            dataModel.setDataId(dataId);


        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @DynamicListData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }



    /**
     * 初始化单对象的数据
     */
    private GDataModel initData(GContext context, DynamicData data) {
        GDataModel dataModel = new GDataModel();

        if(StringUtils.isNotEmpty(data.getFromSql())){

            String sql = data.getFromSql();
            dataModel.setData(dataUtils.generalDataFromSql(sql, true, context.getRequest(), context.getResponse(), context.getProps()));


        } else if(StringUtils.isNotEmpty(data.getFromDataPickerClassName())){


            try {
                Class<? extends IDataPicker> clazz =
                        (Class<? extends IDataPicker>) ClassUtils.getClass(data.getFromDataPickerClassName());
                IDataPicker picker = SpringUtil.getBean(clazz);
                if(picker == null){
                    try {
                        picker = clazz.newInstance();
                    } catch (Exception e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("无法创建类【%s】", clazz.getName()));
                    }
                }
                dataModel.setData(picker.getData(context, null, context.getRequest(), context.getProps()));
            } catch (Exception ex) {
                throw new BaseGViewException(String.format("页面【%s】的 fromDataPickerClassName 找不到类【】 ",
                        context.getViewName(), data.getFromDataPickerClassName()));
            }


        } else if(data.getFromDataPicker() != null){

            dataModel.setData(data.getFromDataPicker().getData(context, null, context.getRequest(), context.getProps()));

        } else if(StringUtils.isNotEmpty(data.getFromJson())){

            String dataId = IdUtils.nextDataId();
            dataModel.setDataId(dataId);
            String json = data.getFromJson().trim();
            if(!json.startsWith("[")){
                throw new BaseGViewException(String.format("页面【%s】的 @DynamicListData 的json结构不对，json内容为【%s】 ",
                        context.getViewName(), json));
            }
            Map<String, Object> map = new GsonBuilder().create().fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
            dataModel.setData(map);

        } else if(StringUtils.isNotEmpty(data.getFromDataSource())){
            String dataId = dataService.findDataIdBySource(data.getFromDataSource());
            if(dataId == null){
                synchronized (this){
                    dataId = dataService.findDataIdBySource(data.getFromDataSource());
                    if(dataId == null){
                        dataId = IdUtils.nextDataId(data.getFromDataSource());
                        String dataSource = data.getFromDataSource();
                        DataSourcePo source = coreService.findDataSourceByName(dataSource);
                        if(source == null){
                            throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                                    , context.getViewName(), data.getFromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
                        }
                        dataService.readySingleDataSource(context, dataId,
                                source.getSourceService(), source.getSourceMethod(), dataSource);
                    }
                }
            }
            dataModel.setDataId(dataId);
        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @GData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }


    /**
     * 初始化下拉的树状数据
     * @return
     */
    private GTreeDataModel initTreeSelectorData(GContext context, DynamicTreeData treeData) {

        GTreeDataModel dataModel = new GTreeDataModel();


        dataModel.setKeyName(treeData.getKeyName());
        dataModel.setValueName(treeData.getValueName());
        if("".equals(treeData.getTitleName())){
            dataModel.setTitleName(treeData.getKeyName());
        } else {
            dataModel.setTitleName(treeData.getTitleName());
        }
        dataModel.setParentKeyName(treeData.getParentKeyName());


        if(StringUtils.isNotEmpty(treeData.getFromEnums())){

            String dataId = dataService.findDataIdBySource(treeData.getFromEnums());
            if(dataId == null){
                synchronized (this){
                    dataId = dataService.findDataIdBySource(treeData.getFromEnums());
                    if(dataId == null){
                        dataId = IdUtils.nextDataId(treeData.getFromEnums());
                        String dataSource = treeData.getFromEnums();
                        DataSourcePo source = coreService.findDataSourceByName(dataSource);
                        if(source == null){
                            throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                                    , context.getViewName(), treeData.getFromEnums()));
                        }
                        dataService.readyEnumsData(context, dataId, treeData.getFromEnums());
                    }
                }
            }
            dataModel.setDataId(dataId);
            return dataModel;
        }

        if(StringUtils.isNotEmpty(treeData.getFromSql())){
            String sql = treeData.getFromSql();
            dataModel.setData(dataUtils.generalDataFromSql(sql, false, context.getRequest(), context.getResponse(), context.getProps()));

        } else if(StringUtils.isNotEmpty(treeData.getFromListDataPickerClassName())){
            try {
                Class<? extends IDataPicker> clazz =
                        (Class<? extends IDataPicker>) ClassUtils.getClass(treeData.getFromListDataPickerClassName());
                IDataPicker picker = SpringUtil.getBean(clazz);
                if(picker == null){
                    try {
                        picker = clazz.newInstance();
                    } catch (Exception e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("无法创建类【%s】", clazz.getName()));
                    }
                }
                dataModel.setData(picker.getData(context, null, context.getRequest(), context.getProps()));
            } catch (Exception ex) {
                throw new BaseGViewException(String.format("页面【%s】的 @GSimpleListData 找不到类【】 ",
                        context.getViewName(), treeData.getFromListDataPickerClassName()));
            }
        } else if(treeData.getFromListDataPicker() != null){

            dataModel.setData(treeData.getFromListDataPicker().getData(context, null, context.getRequest(), context.getProps()));

        } else if(StringUtils.isNotEmpty(treeData.getFromJson())){

            String dataId = IdUtils.nextDataId();
            dataModel.setDataId(dataId);
            String json = treeData.getFromJson().trim();
            if(!json.startsWith("[")){
                throw new BaseGViewException(String.format("页面【%s】的 @DynamicListData 的json结构不对，json内容为【%s】 ",
                        context.getViewName(), json));
            }
            List<Map<String, Object>> list = new GsonBuilder().create().fromJson(json, new TypeToken<List<Map<String, Object>>>(){}.getType());

            String titleName = dataModel.getTitleName();
            if (titleName == null || titleName.isEmpty()) {
                titleName = dataModel.getKeyName();
            }

            // 针对I18N做转换
            if(!StringUtils.isEmpty(titleName)){
                for(Map<String, Object> item : list) {
                    if (item == null) {
                        continue;
                    }
                    if (StringUtils.isEmpty(titleName)) {
                        continue;
                    }
                    Object title = item.get(titleName);
                    if (title != null && title instanceof String) {
                        title = T.t((String) title);
                        item.put(titleName, title);
                    }
                }
            }

            dataModel.setData(list);


        } else if(StringUtils.isNotEmpty(treeData.getFromDataSource())){

            String dataId = dataService.findDataIdBySource(treeData.getFromDataSource());
            if(dataId == null){
                synchronized (this){
                    dataId = dataService.findDataIdBySource(treeData.getFromDataSource());
                    if(dataId == null){
                        dataId = IdUtils.nextDataId(treeData.getFromDataSource());
                        String dataSource = treeData.getFromDataSource();
                        DataSourcePo source = coreService.findDataSourceByName(dataSource);
                        if(source == null){
                            throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                                    , context.getViewName(), treeData.getFromDataSource()));
                        }
                        dataService.readyListDataSource(context, dataId,
                                source.getSourceService(), source.getSourceMethod(), dataSource);
                    }
                }
            }
            dataModel.setDataId(dataId);


        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @DynamicTreeData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }

    private GHiddenModel initHidden(DynamicHidden hidden) {
        GHiddenModel hiddenModel = new GHiddenModel();
        hiddenModel.setKeyName(hidden.getKeyName());
        hiddenModel.setValueName(hidden.getValueName());
        return hiddenModel;
    }

//    private List<String> initBoardName(Class<?> clazz) {
//        List<String> result = new ArrayList<>();
//
//        GView board = clazz.getAnnotation(GView.class);
//
//        if(board == null){
//            GViews boards = clazz.getAnnotation(GViews.class);
//            for(GView b : boards.getValue()){
//                if(result.contains(b.viewName())){
////                    throw new BoardRepeatException(board.viewName());
//                    throw new BaseGViewException(String.format("找到2个重复的view名字【%s】",
//                            board.viewName()));
//                }
//                result.add(b.viewName());
//            }
//        } else {
//            if(result.contains(board.viewName())){
////                throw new BoardRepeatException(board.viewName());
//                throw new BaseGViewException(String.format("找到2个重复的view名字【%s】",
//                        board.viewName()));
//            }
//            result.add(board.viewName());
//        }
//        return result;
//    }


}
